﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TI_BAL;


namespace SecuritySystem
{
    public partial class PurchaseTransaction : Form
    {
        int CASH_ACCOUNT_DB_ID = 3;
        int ACCOUNTS_PAYABLE_ACCOUNT_DB_ID = 5;
        TIEntities dbContext;
        List<ProductType> productTypeList;
        List<ProductSubType> productSubTypeList;

        //public DataGridViewRow selectedRecord = null;

        public PurchaseTransaction()
        {
            InitializeComponent();
            dbContext = new TIEntities();
            FillTypeCombo();
            FillSupplierCombo();
        }

        private void FillTypeCombo()
        {
            productTypeList = (from pt in dbContext.ProductTypes select pt).Distinct().ToList();
            if (productTypeList != null)
            {
                BindDataWithTypeCombo(productTypeList);
            }
            else
            {
                productTypeList = new List<ProductType>();
            }

        }

        private void BindDataWithTypeCombo(List<ProductType> productTypeList)
        {

            this.comboBoxProductType.DataSource = null;
            comboBoxProductType.DisplayMember = "Name";
            comboBoxProductType.ValueMember = "ID";
            comboBoxProductType.DataSource = productTypeList;
            comboBoxProductType.Refresh();
        }


        private void FillSupplierCombo()
        {

            List<Supplier> SupplierList = (from pt in dbContext.Suppliers select pt).ToList<Supplier>();
            if (SupplierList != null)
            {
                BindDataWithSupplierCombo(SupplierList);
            }
            else
            {
                productTypeList = new List<ProductType>();
            }

        }

        private void BindDataWithSupplierCombo(List<Supplier> SupplierList)
        {

            this.comboBoxSupplier.DataSource = null;
            comboBoxSupplier.DisplayMember = "CompanyName";
            comboBoxSupplier.ValueMember = "ID";
            comboBoxSupplier.DataSource = SupplierList;
            comboBoxSupplier.Refresh();
        }


        private void clearFields() {
            this.comboBoxSupplier.SelectedIndex = 0;
            this.comboBoxProductSubType.SelectedIndex = 0;
            this.comboBoxProductType.SelectedIndex = 0;
            this.comboBoxSize.SelectedIndex = 0;

            this.textBoxQuantity.Text = "";
            this.textPrice.Text = "";

            this.dataGridViewSale.Rows.Clear();

            this.radioButtonCash.Checked = true;

        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                //List<SalesTransaction> productSubTypeList = (from pt in dbContext.SalesTransactions select pt).ToList<SalesTransaction>();
                //int invoiceId = 3000 + productSubTypeList.Count;

                foreach (DataGridViewRow rowWalker in this.dataGridViewSale.Rows)
                {
                    int accountId = 0;
                    int SupplierID = int.Parse(rowWalker.Cells["Supplier"].Tag.ToString());
                    Journal journal = new Journal();

                    if (rowWalker.Cells["Transaction"].Value.ToString() == "Cash")
                    {
                        accountId = CASH_ACCOUNT_DB_ID;
                    }
                    else {
                        accountId = ACCOUNTS_PAYABLE_ACCOUNT_DB_ID;
                    }
                    
                    Account account = (from acc in dbContext.Accounts where acc.Account_ID == accountId select acc).FirstOrDefault();
                    journal.Account = account;
                    journal.Journal_Amount = Convert.ToDouble(rowWalker.Cells["TotalPrice"].Value.ToString());
                    journal.Journal_Date = DateTime.Parse(rowWalker.Cells["Date"].Value.ToString());
                    journal.Journal_Description = "Purchase transaction";

                    journal.Product_Type = rowWalker.Cells["ProductType"].Value.ToString();
                    journal.Sub_Type = rowWalker.Cells["SubType"].Value.ToString();
                    journal.Product_Size = rowWalker.Cells["Size"].Value.ToString();
                    journal.Quantity = Convert.ToInt32(rowWalker.Cells["Quantity"].Value.ToString());
                    journal.Per_Item_Price = Decimal.Round((Convert.ToDecimal(rowWalker.Cells["TotalPrice"].Value.ToString()) / Convert.ToDecimal(rowWalker.Cells["Quantity"].Value.ToString())), 2);

                    if (accountId == CASH_ACCOUNT_DB_ID)
                    {
                        journal.TransactionType = "C";
                        journal.Credit_Amount = journal.Journal_Amount;
                        journal.Debit_Amount = 0;
                    }
                    else
                    {
                        journal.TransactionType = "C";
                        journal.Debit_Amount = 0;
                        journal.Credit_Amount = journal.Journal_Amount;
                        journal.Supplier = (from acc in dbContext.Suppliers where acc.ID == SupplierID select acc).FirstOrDefault();
                    }
                    
                    dbContext.AddToJournals(journal);

                    TI_BAL.PurchaseTransaction purchase = new TI_BAL.PurchaseTransaction();
                    
                    //dbContext.pu
                    //trans sale = new PurchaseTransaction();
                    

                    
                    int productTypeID = int.Parse(rowWalker.Cells["ProductType"].Tag.ToString());
                    int productSubTypeID = int.Parse(rowWalker.Cells["SubType"].Tag.ToString());
                    int sizeID = int.Parse(rowWalker.Cells["Size"].Tag.ToString());

                    //sale.Supplier = (from acc in dbContext.Suppliers where acc.ID == SupplierID select acc).FirstOrDefault();
                    purchase.DATE = this.dateTimePickerSaleDate.Value;
                    
                    //sale.INVOICE_ID = invoiceId;
                    try
                    {
                        purchase.PER_UNIT_PRICE  = decimal.Round((Convert.ToDecimal(rowWalker.Cells["TotalPrice"].Value.ToString()) / Convert.ToDecimal(rowWalker.Cells["Quantity"].Value.ToString())),2);

                    }
                    catch {
                        MessageBox.Show("Invalid price or quantity in some order Item");
                        return;
                    }

                    purchase.Supplier = (from acc in dbContext.Suppliers where acc.ID == SupplierID select acc).FirstOrDefault();
                    purchase.ProductType = (from acc in dbContext.ProductTypes where acc.ID == productTypeID select acc).FirstOrDefault();
                    purchase.ProductSubType = (from acc in dbContext.ProductSubTypes where acc.ID == productSubTypeID select acc).FirstOrDefault();
                    purchase.ProductSize = (from acc in dbContext.ProductSizes where acc.ID == sizeID select acc).FirstOrDefault();

                    purchase.QUANITY = decimal.Round(Convert.ToDecimal(rowWalker.Cells["Quantity"].Value.ToString()),2);
                    purchase.Account = (from acc in dbContext.Accounts where acc.Account_ID == accountId select acc).FirstOrDefault();
                    

                    
                    dbContext.AddToPurchaseTransactions(purchase);

                    Inventory invObj = new Inventory();

                    invObj.Description= "Purchase transaction";
                    invObj.ItemName=rowWalker.Cells["ProductType"].Value.ToString();
                    invObj.Price=decimal.Round(decimal.Parse(purchase.PER_UNIT_PRICE.ToString()),2);
                    invObj.ProductSize=purchase.ProductSize;
                    invObj.ProductSubType=purchase.ProductSubType;
                    invObj.ProductType=purchase.ProductType;
                    invObj.Quantity=int.Parse(purchase.QUANITY.ToString());
                    invObj.PurchaseDate=DateTime.Parse(rowWalker.Cells["Date"].Value.ToString());;
                    invObj.Supplier=purchase.Supplier;

                    dbContext.AddToInventories(invObj);
                    
                    dbContext.SaveChanges();

                    
                    
                }
                clearFields();
            }
            catch {
                MessageBox.Show("There was some error in saving transaction, please see if there some error in data");
                clearFields();
            }
             
            
        }

        private void PurchaseTransaction_Load(object sender, EventArgs e)
        {
            this.dateTimePickerSaleDate.Value = DateTime.Now;
            
            
                    
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBoxProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillSubTypeCombo();
            FillSizeCombo();
        }

        private void FillSubTypeCombo()
        {
            int selectedTypeId = Convert.ToInt32(this.comboBoxProductType.SelectedValue.ToString());
            List<ProductSubType> productSubTypeList = (from pt in dbContext.ProductSubTypes where pt.ProductTypeID == selectedTypeId select pt).ToList<ProductSubType>();
            if (productSubTypeList != null)
            {
                BindDataWithSubTypeCombo(productSubTypeList);
            }
            else
            {
                productSubTypeList = new List<ProductSubType>();
            }
        }

        private void BindDataWithSubTypeCombo(List<ProductSubType> productSubTypeList)
        {

            this.comboBoxProductSubType.DataSource = null;
            comboBoxProductSubType.DisplayMember = "Name";
            comboBoxProductSubType.ValueMember = "ID";
            comboBoxProductSubType.DataSource = productSubTypeList;
            comboBoxProductSubType.Refresh();
        }

        private void comboBoxProductSubType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        private void FillSizeCombo()
        {
            int selectedTypeId = Convert.ToInt32(this.comboBoxProductType.SelectedValue.ToString());
            List<ProductSize> productSizeList = (from pt in dbContext.ProductSizes where pt.TypeID == selectedTypeId select pt).ToList<ProductSize>();
            if (productSizeList != null)
            {
                BindDataWithSizeCombo(productSizeList);
            }
            else
            {
                productSizeList = new List<ProductSize>();
            }
        }

        private void BindDataWithSizeCombo(List<ProductSize> productSizeList)
        {

            this.comboBoxSize.DataSource = null;
            comboBoxSize.DisplayMember = "Name";
            comboBoxSize.ValueMember = "ID";
            comboBoxSize.DataSource = productSizeList;
            comboBoxSize.Refresh();
        }

        private void buttonAddOrder_Click(object sender, EventArgs e)
        {
            if (this.comboBoxSupplier.SelectedIndex == -1)
            {
                MessageBox.Show("Suppier does not exist, please select the correct suplier");
                return;
            }

            if (this.comboBoxProductType.SelectedIndex == -1)
            {                
                MessageBox.Show("Product does not exist, please select the correct product");
                return;
            }

            if (this.textPrice.Text.Trim() == "" || this.textBoxQuantity.Text.Trim() == "")
            {
                MessageBox.Show("Price and quantity are Mendatory fields");
                return;
            }

            DataGridViewRow rowToAdd = new DataGridViewRow();
            int index = this.dataGridViewSale.Rows.Add(rowToAdd);

            this.dataGridViewSale.Rows[index].Cells["Supplier"].Value = this.comboBoxSupplier.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["Supplier"].Tag = this.comboBoxSupplier.SelectedValue.ToString();
            this.dataGridViewSale.Rows[index].Cells["ProductType"].Value = this.comboBoxProductType.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["ProductType"].Tag = this.comboBoxProductType.SelectedValue.ToString();
            this.dataGridViewSale.Rows[index].Cells["SubType"].Value = this.comboBoxProductSubType.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["SubType"].Tag = this.comboBoxProductSubType.SelectedValue.ToString();
            this.dataGridViewSale.Rows[index].Cells["Size"].Value = this.comboBoxSize.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["Size"].Tag = this.comboBoxSize.SelectedValue.ToString();

            this.dataGridViewSale.Rows[index].Cells["Quantity"].Value = this.textBoxQuantity.Text;
            this.dataGridViewSale.Rows[index].Cells["TotalPrice"].Value = this.dataGridViewSale.Rows[index].Cells["TotalPrice"].Value = (double.Parse(this.textPrice.Text) * double.Parse(this.textBoxQuantity.Text)).ToString();
            this.dataGridViewSale.Rows[index].Cells["Date"].Value = this.dateTimePickerSaleDate.Value;

            if (this.radioButtonCash.Checked == true)
            {
                this.dataGridViewSale.Rows[index].Cells["Transaction"].Value = "Cash";
            }
            else
            {
                this.dataGridViewSale.Rows[index].Cells["Transaction"].Value = "Credit";
            }



        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void label1Supplier_Click(object sender, EventArgs e)
        {

        }

        private void label10_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                this.dataGridViewSale.Rows.Remove(this.dataGridViewSale.SelectedRows[0]);
            }
            catch { }
            //this.dataGridViewSale.SelectedRows[0].Index
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
